package netTools;

/**
 * Used for file transfers. PortManager gives a thread a free port number which the latter
 * can wait for incoming connections. If all ports are busy thread will wait till one frees.
 * @author pasquale
 *
 */
public class PortManager {
	
	private int BASE_PORT = 2000; //default base port
	private int PORT_LEN = 200; //default port length
	
	public PortManager(){
		current_port = BASE_PORT;
	}
	
	public PortManager(int basePort,int portLength){
		BASE_PORT = basePort;
		PORT_LEN = portLength;
		current_port = BASE_PORT;
	}
	
	public synchronized int getPortNumber(){
		while(current_port == (BASE_PORT+PORT_LEN))
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		int port = current_port;
		current_port++;
		return port;
	}
	
	public synchronized void freePort(){
		current_port--;
		this.notifyAll();
	}
	
	private int current_port;
	

}
